from typing import Dict, Any, List

import cv2
import numpy as np
from app.utils.logger import get_logger

logger = get_logger(__name__)


# 印章文本检测模块


class SealTextDetectionModule:
    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(SealTextDetectionModule, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            logger.info("Initializing SealTextDetectionModule")
            self._initialized = True

    def detect(self, image_data: bytes) -> Dict[str, Any]:
        """
        检测印章文本

        Args:
            image_data: 图像字节数据

        Returns:
            印章文本检测结果
        """
        try:
            # 将字节数据转换为OpenCV图像
            nparr = np.frombuffer(image_data, np.uint8)
            img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

            # 检测印章区域
            seal_regions = self._detect_seal_regions(img)

            # 在印章区域内检测文本
            seal_texts = []
            for region in seal_regions:
                texts = self._detect_text_in_seal(img, region)
                seal_texts.extend(texts)

            return {
                "seal_regions": seal_regions,
                "seal_texts": seal_texts,
                "total_seals": len(seal_regions)
            }

        except Exception as e:
            raise RuntimeError(f"Seal text detection failed: {str(e)}")

    def _detect_seal_regions(self, img) -> List[Dict]:
        """检测印章区域"""
        # 模拟印章检测结果
        return [
            {
                "bbox": [300, 300, 500, 500],
                "confidence": 0.88,
                "shape": "circular"
            }
        ]

    def _detect_text_in_seal(self, img, region: Dict) -> List[Dict]:
        """在印章区域内检测文本"""
        # 模拟印章文本检测结果
        return [
            {
                "text": "公章",
                "bbox": [350, 350, 450, 380],
                "confidence": 0.90
            }
        ]
